package com.ztesoft.book.common.utils.base;


import com.ztesoft.book.common.utils.exception.ServiceException;

/**
 * @author sunhanyue
 * 简易雪花算法
 * @date 2019/9/25
 */
public final class SnowFlakeGenerator {
    private SnowFlakeGenerator() {

    }

    /**
     * 起始的时间戳
     */
    private static final long START_STMP = 1480166465631L;

    /**
     * 每一部分占用的位数
     * 序列号占用的位数 12
     * 机器标识占用的位数 5
     * 数据中心占用的位数 5
     */
    private static final long SEQUENCE_BIT = 12;
    private static final long MACHINE_BIT = 5;
    private static final long DATACENTER_BIT = 5;

    /**
     * 每一部分的最大值
     */
    private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private static final long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
    /**
     * 数据中心
     */
    private static long datacenterId = 2L;
    /**
     * 机器标识
     */
    private static long machineId = 3L;
    /**
     * 序列号
     */
    private static long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private static long lastStmp = -1L;

    /**
     * 产生下一个ID
     *
     * @return long
     */
    public static synchronized long nextId() {
        long currStmp = getNewTmp();
        if (currStmp < lastStmp) {
            throw new ServiceException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStmp == lastStmp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        }
        else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastStmp = currStmp;

        return (currStmp - START_STMP) << TIMESTMP_LEFT | datacenterId << DATACENTER_LEFT | machineId << MACHINE_LEFT | sequence;
    }

    private static long getNextMill() {
        long mill = getNewTmp();
        while (mill <= lastStmp) {
            mill = getNewTmp();
        }
        return mill;
    }

    private static long getNewTmp() {
        return System.currentTimeMillis();
    }

    public static String generateIdStr() {
        return String.valueOf(SnowFlakeGenerator.nextId());
    }

    public static Long generateId() {
        return SnowFlakeGenerator.nextId();
    }

}
